﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Linq.Expressions;
using System.ComponentModel.Composition;
using Kooboo.Domain;

namespace Kooboo.Commerce.Repositories.Products
{
    [Export(typeof(IEntityUpdateCommand<IProduct>))]
    public class ProductUpdateCommand:EntityUpdateCommand<IProduct>
    {
        protected override string TableName
        {
            get {
                return "Product";
            }
        }

        protected override KeyValuePair<string, object> BuildSetMember(string fieldName, object value)
        {
            if (fieldName == "Brand")
            {
                if (value == null)
                {
                    return new KeyValuePair<string, object>("BrandId", null);
                }
                else
                {
                    return new KeyValuePair<string, object>("BrandId", ((IBrand)value).Id);
                }
            }
            else if (fieldName == "ProductType")
            {
                if (value == null)
                {
                    return new KeyValuePair<string, object>("ProductTypeId", null);
                }
                else
                {
                    return new KeyValuePair<string, object>("ProductTypeId", ((IProductType)value).Id);
                }
            }
            else if (fieldName == "Tax")
            {
                if (value == null)
                {
                    return new KeyValuePair<string, object>("TaxId", null);
                }
                else
                {
                    return new KeyValuePair<string, object>("TaxId", ((IProductType)value).Id);
                }
            }
            else
            {
                return base.BuildSetMember(fieldName, value);
            }
            
        }

    

        protected override string BuildCondition()
        {
            var ids = this.EntitySet.Select(i => i.Id).ToArray();

            if (ids.Length == 0)
            {
                return " 1=2 "; 
            }
            else
            {
                return " Id in (" + string.Join(", ", ids) + ") ";
            }
        }
    }
}
